<!DOCTYPE html>
<html>
<head>
    <!-- 声明使用utf-8编码 -->
    <meta http-equiv="content-type" content="txt/html; charset=utf-8"/>
    <meta name="referrer" content="never"/>

    <!-- 使用EL表达式(${app_path})查出项目路径 -->
    <!-- jquery 核心 JavaScript 文件 -->
    <script src="/static/js/jquery-3.5.1.min.js"></script>
    <!-- Underscore-1.12.0 JS函数扩展库 JavaScript 文件 -->
    <script type="text/javascript" src="/static/js/Underscore-1.12.0.min.js"></script>
    <!-- Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <!-- Bootstrap 次要 CSS 文件 -->
    <!--    <link  href="/web/static/bootstrap-3.3.7-dist/fonts/glyphicons-halflings-regular.woff">-->
    <!--    <link  href="/web/static/bootstrap-3.3.7-dist/fonts/glyphicons-halflings-regular.woff2">-->
    <!--    <link  href="/web/static/bootstrap-3.3.7-dist/fonts/glyphicons-halflings-regular.ttf">-->
    <!-- Bootstrap 核心 JavaScript 文件 -->
    <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <!-- Bootstrap alert 扩展 JavaScript 文件 -->
    <script src="/static/bootstrap-alert-extend/bootstrap-alert-extend.js"></script>
    <!-- Bootstrap-select 核心 CSS 文件 -->
    <link rel="stylesheet" href="/static/bootstrap-select-1.13.9/dist/css/bootstrap-select.min.css">
    <!-- Bootstrap-select 核心 JS 文件 -->
    <script src="/static/bootstrap-select-1.13.9/js/bootstrap-select.js"></script>
    <!-- Bootstrap-table 核心 CSS 文件 src/main/webapp/static/bootstrap-table-1.18.2/dist/bootstrap-table.css-->
    <link rel="stylesheet" href="/static/bootstrap-table-1.18.2/dist/bootstrap-table.min.css">
    <!-- Bootstrap-table 核心 JS 文件 -->
    <script src="/static/bootstrap-table-1.18.2/dist/bootstrap-table.min.js"></script>
    <!-- 工具函数 JS 文件 -->
    <script src="/static/js/util.js"></script>
    <!-- 接口url链接 JS 文件 -->
    <script src="/static/js/urlInterface.js"></script>
    <!-- 信息码 JS 文件 -->
    <script src="/static/js/statusCode.js"></script>

    <style type="text/css">

        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            background: #eaeaea;
        }

        /*div[class|=col]{*/
        /*    border: 1px solid;*/
        /*}*/
        a:hover, a:focus, a:link, a:visited, a:active {
            text-decoration: none;
        }
        /* 链接 */
        .panel-default a:link {
            color: #555;
        }
        /* 掠过*/
        .panel-default a:hover  {
            color: #111;
            font-weight: bold;
        }
        /* 掠过 */
        .panel-default a:hover h4  {
            color: #111;
            font-weight: bold;
        }
    </style>

</head>

<body>

<div class="modal fade" tabindex="-1" role="dialog" id="pwdModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">

                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h2 class="text-center">修改密码</h2>

            </div>
            <div class="modal-body">
                <!--修改密码表单-->
                <div class="row" style="margin-top: 20px;">
                    <div class="col-sm-6 col-sm-offset-3">
                        <form id="login_form">
                            <div class="form-group">
                                <label for="password">原密码：</label>
                                <input type="password" class="form-control" name="password" id="password"
                                       placeholder="请输入密码">
                                <span class="help-block"></span>
                            </div>
                            <div class="form-group">
                                <label for="password2">新密码：</label>
                                <input type="password" class="form-control" name="password2" id="password2"
                                       placeholder="请输入新密码">
                                <span class="help-block"></span>
                            </div>
                        </form>
                        <button id="change_password_btn" class="btn btn-primary"
                                style=" margin-top:10px;float:left;width: 98%;" disabled>确认修改
                        </button>

                    </div>
                </div>

            </div>
            <div class="modal-footer">
                <!--                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                <!--                <button type="button" class="btn btn-primary">Save changes</button>-->
            </div>
        </div>
    </div>
</div>

<!-- 等待加载用的模态框 -->
<div class="modal fade" id="wait_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <ul class="list-group">
                <li class="list-group-item list-group-item-info"><h4 class="modal-title">提示信息</h4></li>
                <li style="list-style-type: none;">
                    <div class="modal-body">等待数据加载完成...</div>
                </li>
            </ul>
        </div>
    </div>
</div>
<div style="height: 100%">
    <nav class="navbar-default">
        <div class="container">
            <!--导航条 -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                        data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#"> <strong>摸鱼人事管理系统</strong> <small> V0.6</small> </a>
            </div>

            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">欢迎：<span id="welcome_sp" class="text-danger">XXX</span></a></li>
                    <li><a href="/index"><span class="glyphicon glyphicon-home" aria-hidden="true"></span>主页</a>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                           aria-expanded="false">
                            <span class="glyphicon glyphicon-user" aria-hidden="true"></span> 个人中心<span
                                class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li id="change_password_li"><a href="javascript:;" id="update-pwd"><span
                                    class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 修改密码</a>
                            </li>
                            <li role="separator" class="divider"></li>
                            <li id="logout_li"><a href="#"><span class="glyphicon glyphicon-log-out"
                                                                 aria-hidden="true"></span> 注销登录</a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>


    <!--页面中心内容-->

    <div class="row" style="height: 90%">
        <div class="col-sm-2" >
            <!--菜单组件-->
            <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"
                 style="padding:10px 0px 10px 15px;">
<!--  菜单例子  -->
<!--                <div class="panel panel-default">-->
<!--                    <div class="panel-heading" role="tab" id="heading1" style="text-align:center;padding: 0px;">-->
<!--                        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse1"-->
<!--                           aria-expanded="true" aria-controls="collapse1" class="">-->
<!--                            <h4 class="panel-title" style="padding: 10px;">权限管理</h4>-->
<!--                        </a>-->
<!--                    </div>-->
<!--                    <div id="collapse1" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading1"-->
<!--                         style="text-align: center;" aria-expanded="true">-->
<!--                        <div class="panel-body">-->
<!--                            <ul class="list-group" style="cursor:pointer">-->
<!--                                <li class="list-group-item" style="padding: 0px;"><a href="javascript:;"-->
<!--                                                                                     style="padding:10px 15px;width: 100%;height: 100%;display: inline-table;">用户管理</a>-->
<!--                                </li>-->
<!--                                <li class="list-group-item" style="padding: 0px;"><a href="javascript:;"-->
<!--                                                                                     style="padding:10px 15px;width: 100%;height: 100%;display: inline-table;">角色管理</a>-->
<!--                                </li>-->
<!--                            </ul>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->
<!--                <div class="panel panel-default">-->
<!--                    <div class="panel-heading" role="tab" id="heading2" style="text-align:center;padding: 0px;">-->
<!--                        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse2"-->
<!--                           aria-expanded="false" aria-controls="collapse2" class="collapsed">-->
<!--                            <h4 class="panel-title" style="padding: 10px;">部门职能</h4>-->
<!--                        </a>-->
<!--                    </div>-->
<!--                    <div id="collapse2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading2"-->
<!--                         style="text-align: center; height: 0px;" aria-expanded="false">-->
<!--                        <div class="panel-body">-->
<!--                            <ul class="list-group" style="cursor:pointer">-->
<!--                                <li class="list-group-item" style="padding: 0px;"><a href="javascript:;"-->
<!--                                                                                     style="padding:10px 15px;width: 100%;height: 100%;display: inline-table;">部门管理</a>-->
<!--                                </li>-->
<!--                                <li class="list-group-item" style="padding: 0px;"><a href="javascript:;"-->
<!--                                                                                     style="padding:10px 15px;width: 100%;height: 100%;display: inline-table;">职位管理</a>-->
<!--                                </li>-->
<!--                                <li class="list-group-item" style="padding: 0px;"><a href="javascript:;"-->
<!--                                                                                     style="padding:10px 15px;width: 100%;height: 100%;display: inline-table;">员工管理</a>-->
<!--                                </li>-->
<!--                            </ul>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->

            </div>
        </div>

        <div id="main">
            <div class="col-sm-10">
                <!--中心内容-->


            </div>
        </div>

    </div>
</div>
</body>
<script>
    var initPage_finish = false;
    var bindOnEvent_finish = false;
    var username = "null";

    $(function () {
        startWaiting();
        //初始化页面
        initPage();
        //给控件绑定事件
        bindOnEvent();
        checkIsFinish();
    });

    /**
     * 该方法用于开始等待页面数据填充
     */
    function startWaiting() {
        //弹出等待模态框
        $('#wait_modal').modal({
            show: true,
            backdrop: 'static'
        });
    }

    /**
     * 该方法用于循环等待并判断是否已结束了页面加载，若是则结束，若否则继续等待
     */
    function checkIsFinish() {
        let intervalID = setInterval(function () {
            console.log("持续等待页面加载...");

            if (initPage_finish && bindOnEvent_finish) {//如果可以结束，则结束
                console.log("页面加载完成!");
                //关闭等待模态框
                $('#wait_modal').modal('hide');
                //欢迎提示
                alertUtil.message("欢迎回来！用户<strong>[" + username + "]</strong>！", "success");
                clearInterval(intervalID);//结束循环
            }
        }, 200);
    }

    /**
     * 该方法用于初始化该主框架页面
     */
    function initPage() {
        //获取accessToken
        let accessToken = sessionStorage.getItem("accessToken");
        console.log("初始化index时，accessToken为:"+accessToken)

        //如果accessToken无效，则直接返回登录页面
        if (accessToken == null || accessToken === "undefined") {
            // if ( false ){
            window.location.href = to_login + "?code=" + UNAUTHORIZED;//跳转到登录页面，并提示没有认证
        } else {
            //构建页面
            $.ajax({
                url: permissionInterface,//非Rest
                type: "GET",
                beforeSend: function (XMLHttpRequest) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    console.log("请求权限的结果为:")
                    console.log(result)

                    if (result.code == 200){
                        // 构建头部栏
                        let user = result.dataMap.user;
                        build_header_bar(user);
                        // 构建侧边栏
                        let resourceParentList = result.dataMap.user.resourceParentList;
                        build_left_bar(resourceParentList);
                    }else {
                        //退回登录页面，并提示状态码
                        window.location.href = to_login + "?code=" + LOGIN_EXPIRED;
                    }
                },
                error: function () {

                },
                complete() {
                    initPage_finish = true;
                }
            });
        }


    }

    /**
     * 构建头部栏
     */
    function build_header_bar(user) {
        username = user.username; //获取用户名
        let nickname = user.nickname; //获取昵称
        //设置昵称
        $("#welcome_sp").empty().append(nickname);
    }

    /**
     * 构建左侧栏
     */
    function build_left_bar(resourceParentList) {
        // 构建侧边栏
        let $accordionDiv = $("#accordion");
        let firstResource = null;//第一个资源(首要显示的页面)
        let nowNumber = 1;//用于给id更改不同的名字用

        $.each(resourceParentList, function (index, item) {
            let $panelDiv = $("<div class=\"panel panel-default\"></div>");
            let collapseNamePrefix = "collapse";
            let collapseName = collapseNamePrefix + nowNumber;
            let headingName = "heading" + nowNumber;

            let $panelHeadingDiv = $(
                "<div class=\"panel-heading\" role=\"tab\" id=\"" + headingName + "\" style=\"text-align:center;padding: 0px;\">\n" +
                "<a role=\"button\" data-toggle=\"collapse\"  data-parent=\"#accordion\" href=\"#" + collapseName + "\" aria-expanded=\"true\" aria-controls=\"" + collapseName + "\">\n" +
                "<h4 class=\"panel-title\" style=\"padding: 10px;\">" + item.title + "</h4>\n" +
                "</a>\n" +
                "</div>");

            let $panelCollapseDiv = $(
                "<div id=\"" + collapseName + "\" class=\"panel-collapse collapse\" role=\"tabpanel\" aria-labelledby=\"" + headingName + "\" style=\"text-align:center\">\n" +
                "<div class=\"panel-body\">\n" +
                "<ul class=\"list-group\"></ul>\n" +
                "</div>\n" +
                " </div>");

            //遍历子标题资源
            $.each(item.resourceList, function (index, item) {
                if (firstResource == null) {//如果firstResource还未定义，则可以直接加载该第一个页面
                    firstResource = item.resource;
                    //$("#main").load(firstResource);//加载页面
                }
                let $titleLi = $(
                    "<li class=\"list-group-item\" style=\"padding: 0px;\">" +
                    "<a href=\"javascript:;\" style=\"" +
                    "padding:10px 15px;" +
                    "width: 100%;" +
                    "height: 100%;" +
                    "display: inline-table;" +
                    "\">" + item.resource_name +
                    "</a>" +
                    "</li>");

                $titleLi.click(function () {
                    //加载页面之前先存储先前的url
                    sessionStorage.setItem("lastUrl", item.resource);
                    $.ajax({//请求修改密码
                        url: item.resource,
                        type: "GET",
                        beforeSend: function (XMLHttpRequest) {
                            //在请求头部设置accessToken
                            XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                        },
                        //请求成功后的回调函数
                        //result是请求成功后返回的Json结果
                        success: function (result) {
                            // console.log(result);
                            $("#main").html(result);//加载网页
                        },
                        error: function () {
                            alertUtil.message("服务器后端未响应!", "danger");
                        }
                    });
                });
                $panelCollapseDiv.find("ul").append($titleLi);
            });
            nowNumber++;

            $panelDiv.append($panelHeadingDiv);
            $panelDiv.append($panelCollapseDiv);

            $accordionDiv.append($panelDiv);


        });
    }


    /**
     * 该方法用于弹出等待模态框
     */
    function show_wait_modal() {
        //弹出等待模态框
        $('#wait_modal').modal({
            show: true,
            backdrop: 'static'
        });
    }

    /**
     * 该方法用于关闭等待模态框
     */
    function close_wait_modal() {
        //关闭等待模态框
        $('#wait_modal').modal('hide');
    }

    /**
     * 该方法用于给控件绑定事件
     */
    function bindOnEvent() {
        // sessionStorage.setItem("bindOnEvent_finish","false");
        bindOnEvent_finish = false;

        //给注销按钮绑定点击事件
        $("#logout_li").click(function () {
            let statusCode;
            $.ajax({//请求注销登录
                url: logoutInterface,
                type: "POST",
                beforeSend: function (XMLHttpRequest) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    console.log(result);
                    if (result.code == 200) {
                        // alertUtil.message(result.msg);
                        statusCode = LOGOUT_SUCCESS;
                    } else {
                        // alertUtil.message(result.msg, "danger");
                        statusCode = TOKEN_NOT_EXIST;
                    }
                },
                error: function () {
                    alertUtil.message("服务器后端未响应!", "danger");
                    statusCode = BACKEND_NO_RESPOND;
                },
                complete: function () {
                    sessionStorage.clear();//直接清除所有属性
                    window.location.href = to_login + "?code=" + statusCode;//跳转到登录页面
                }
            });
        });

        $("#update-pwd").click(function () {
            $('#pwdModal').modal({
                show: true,
                backdrop: 'static'
            });
        });

        //设置改密码输入框们的点击事件
        $("input").bind("input propertychange", function () {
            checkChangeForm();
        });

        //设置修改密码按钮的点击事件
        $("#change_password_btn").click(function () {
            // let userId = sessionStorage.getItem("userID");
            let password = $("input[name='password']").val();
            let password2 = $("input[name='password2']").val();
            let passwordData = {
                password: password,
                password2: password2
            };
            let passwordJsonData = JSON.stringify(passwordData);
            console.log("passwordData:" + passwordData);
            console.log("passwordJsonData:" + passwordJsonData);

            $.ajax({//请求修改密码
                url: changePasswordInterface,
                data: passwordJsonData,
                contentType: 'application/json;charset=utf-8',
                type: "POST",
                beforeSend: function (XMLHttpRequest) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    console.log(result);
                    if (result.code == 200) {
                        alertUtil.message(result.msg);
                        $("#pwdModal").modal('hide');//关闭模态框
                    } else {
                        console.info(result.dataMap.errorMap);
                        alertUtil.message(result.msg, "danger");
                    }
                },
                error: function () {
                    alertUtil.message("服务器后端未响应!", "danger");
                }
            });
        });
        // sessionStorage.setItem("bindOnEvent_finish","true");
        bindOnEvent_finish = true;
    }

    /**
     * 该方法用于检查表格，给后端传输数据，并返回验证信息
     */
    function checkChangeForm() {
        //开始检查前必须将注册按钮给禁用
        $("#change_password_btn").attr("disabled", "");
        // let userId = sessionStorage.getItem("userID");
        let password = $("input[name='password']").val();
        let password2 = $("input[name='password2']").val();
        let passwordData = {
            password: password,
            password2: password2
        };
        let passwordJsonData = JSON.stringify(passwordData);
        console.log("passwordData:" + passwordData);
        console.log("passwordJsonData:" + passwordJsonData);

        $.ajax({//请求验证修改密码信息
            url: changePasswordInterface,
            data: passwordJsonData,
            contentType: 'application/json;charset=utf-8',
            type: "PUT",
            beforeSend: function (XMLHttpRequest) {
                //在请求头部设置accessToken
                XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
            },
            //请求成功后的回调函数
            //result是请求成功后返回的Json结果
            success: function (result) {
                console.log(result);
                if (result.code == 200) {
                    clearAllErrors();//先清除所有错误
                    $("#change_password_btn").removeAttr("disabled");//去除按钮的disabled
                } else {
                    //获取错误信息对象
                    let errorMap = result.dataMap.errorMap;
                    //给输入框显示信息
                    console.info(errorMap);
                    clearAllErrors();//先清除所有错误
                    for (let inputName in errorMap) {//js原生遍历
                        console.log("错误信息为:" + inputName + ":" + errorMap[inputName]);//键值对
                        showSingleError(inputName, errorMap[inputName]);
                    }
                }
            },
            error: function () {
                alertUtil.message("服务器后端未响应!", "danger");
            }
        });
    }

    /**
     * 该方法用于给控件下方的位置显示错误
     */
    function showSingleError(inputName, errorMsg) {
        //添加错误显示并添加错误信息
        $("input[name='" + inputName + "']").parents(".form-group").addClass("has-error");
        $("input[name='" + inputName + "']").next().append(errorMsg);
    }

    /**
     * 该方法用于给所有控件下方的位置清除错误
     */
    function clearAllErrors() {
        $("input").parents(".form-group").removeClass("has-error");
        $("input").next().empty();
    }
</script>
</html>